package io.qifan.desktop.server.infrastructure.config;

import cn.dev33.satoken.stp.StpUtil;
import com.sun.security.auth.UserPrincipal;
import io.qifan.desktop.common.constants.ResultCode;
import io.qifan.desktop.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.List;
import java.util.Map;

@Slf4j
public class UserHandShakeHandler extends DefaultHandshakeHandler {
    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        List<String> deviceId = request.getHeaders().get("deviceId");
        if (CollectionUtils.isEmpty(deviceId)) {
            throw new BusinessException(ResultCode.ParamSetIllegal, "设备不存在");
        }
        log.info("当前登录用户id：{}，设备id：{}", StpUtil.getLoginIdAsString(),
                deviceId.get(0));
        return new UserPrincipal(deviceId.get(0));
    }
}
